package com.time.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.base.Preconditions;
import com.time.auth.application.convent.AuthAdminUserDTOConverter;
import com.time.auth.common.enums.AuthUserTypeEnum;
import com.time.auth.domain.entity.AuthAdminUserBO;
import com.time.auth.domain.service.AuthAdminUserDomainService;
import com.time.auth.entity.AuthAdminUserDTO;
import com.time.auth.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 管理员用户控制层类
 *
 * @author: HuangQi
 * @date: Created in 16:05 2025/9/29
 * @description: 管理员用户控制层
 */
@Slf4j
@RestController
@RequestMapping("/adminUser/")
public class AdminUserController {

    @Autowired
    private AuthAdminUserDomainService authAdminUserDomainService;

    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthAdminUserDTO authAdminUserDTO, @RequestParam("user_type") Integer userType) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.register.dto:{}", authAdminUserDTO);
            }
            // 参数校验
            checkAdminUserInfo(authAdminUserDTO);

            // 调用领域层
            AuthAdminUserBO authAdminUserBO = AuthAdminUserDTOConverter.INSTANCE.convertDTOToBO(authAdminUserDTO);
            Boolean addResult = authAdminUserDomainService.register(authAdminUserBO, userType);

            // 返回结果
            return Result.ok(addResult);
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.register.error:{}", e.getMessage(), e);
            return Result.fail("添加管理员用户失败");
        }

    }

    /**
     * 更新用户信息
     *
     * @param authAdminUserDTO 更新用户信息
     * @return 更新结果
     */
    @PostMapping("update")
    public Result<Boolean> update(@RequestBody AuthAdminUserDTO authAdminUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.update.dto:{}", authAdminUserDTO);
            }

            // 参数校验
            Preconditions.checkNotNull(authAdminUserDTO.getAdminId(), "管理员用户id不能为空");
            checkAdminUserInfo(authAdminUserDTO);

            // 调用领域层
            AuthAdminUserBO authAdminUserBO = AuthAdminUserDTOConverter.INSTANCE.convertDTOToBO(authAdminUserDTO);
            Boolean updateResult = authAdminUserDomainService.update(authAdminUserBO);

            // 返回结果
            return Result.ok(updateResult);
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.update.error:{}", e.getMessage(), e);
            return Result.fail("更新管理员用户信息失败");
        }
    }

    /**
     * 删除用户
     *
     * @param authAdminUserDTO 删除用户信息
     * @return 删除结果
     */
    @PostMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthAdminUserDTO authAdminUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.delete.dto:{}", authAdminUserDTO);
            }

            // 参数校验
            Preconditions.checkNotNull(authAdminUserDTO.getAdminId(), "管理员用户id不能为空");

            // 调用领域层
            AuthAdminUserBO authAdminUserBO = AuthAdminUserDTOConverter.INSTANCE.convertDTOToBO(authAdminUserDTO);
            Boolean updateResult = authAdminUserDomainService.delete(authAdminUserBO);

            // 返回结果
            return Result.ok(updateResult);
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.delete.error:{}", e.getMessage(), e);
            return Result.fail("删除管理员用户失败");
        }
    }


    /**
     * 用户启用/禁用
     *
     * @param authAdminUserDTO 用户信息
     * @return 启用/禁用结果
     */
    @PostMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthAdminUserDTO authAdminUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.changeStatus.dto:{}", authAdminUserDTO);
            }

            // 参数校验
            Preconditions.checkNotNull(authAdminUserDTO.getAdminId(), "管理员用户id不能为空");
            Preconditions.checkNotNull(authAdminUserDTO.getStatus(), "管理员用户状态不能为空");

            // 调用领域层
            AuthAdminUserBO authAdminUserBO = AuthAdminUserDTOConverter.INSTANCE.convertDTOToBO(authAdminUserDTO);
            Boolean updateResult = authAdminUserDomainService.update(authAdminUserBO);

            // 返回结果
            return Result.ok(updateResult);
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.changeStatus.error:{}", e.getMessage(), e);
            return Result.fail("启用/禁用管理员用户失败");
        }
    }


    /**
     * 获取用户信息
     *
     * @param authAdminUserDTO 需要获取的用户信息
     * @return 获取用户信息
     */
    @PostMapping("getUserInfo")
    public Result<AuthAdminUserDTO> getUserInfo(@RequestBody AuthAdminUserDTO authAdminUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.getUserInfo.dto:{}", authAdminUserDTO);
            }

            // 参数校验
            Preconditions.checkArgument(!StringUtils.isBlank(authAdminUserDTO.getUserName()), "用户名称不能为空");

            // 调用领域层
            AuthAdminUserBO authAdminUserBO = AuthAdminUserDTOConverter.INSTANCE.convertDTOToBO(authAdminUserDTO);
            AuthAdminUserBO userInfo = authAdminUserDomainService.getUserInfo(authAdminUserBO);

            // 返回结果
            return Result.ok(AuthAdminUserDTOConverter.INSTANCE.convertBOToDTO(userInfo));
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.getUserInfo.error:{}", e.getMessage(), e);
            return Result.fail("获取管理员用户信息失败");
        }
    }

    /**
     * 用户登出
     *
     * @param userName 用户名称
     * @return 登出结果
     */
    @GetMapping("logout")
    public Result logout(@RequestParam("userName") String userName) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.logout.userName:{}", userName);
            }

            // 参数校验
            Preconditions.checkArgument(!StringUtils.isBlank(userName), "管理员用户名称不能为空");

            // 调用领域层
            String openId = AuthUserTypeEnum.ADMIN.getDesc() + userName;
            StpUtil.logout(openId);

            // 返回结果
            return Result.ok();
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.logout.error:{}", e.getMessage(), e);
            return Result.fail("管理员用户登出失败");
        }
    }

    /**
     * 用户登录
     *
     * @param validCode 验证码
     * @return 登录结果
     */
    @GetMapping("doLogin")
    public Result doLogin(@RequestParam("userName") String userName, @RequestParam("password") String password) {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.doLogin.userName:{}, password:{}", userName, password);
            }

            // 参数校验
            Preconditions.checkArgument(!StringUtils.isBlank(userName), "管理员用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(password), "管理员密码不能为空");

            // 调用领域层
            SaTokenInfo tokenInfo = authAdminUserDomainService.doLogin(userName, password);

            // 返回结果
            return Result.ok(Objects.isNull(tokenInfo) ? "登录失败" : tokenInfo);
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail("管理员用户登录失败");
        }
    }

    /**
     * 查询用户登录状态
     *
     * @return 登录状态
     */
    @RequestMapping("isLogin")
    public Result isLogin() {
        try {
            if (log.isInfoEnabled()) {
                log.info("AdminUserController.isLogin");
            }
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            log.info("AdminUserController.isLogin.tokenInfo:{}", tokenInfo);

            // 返回结果
            String loginStatus = "当前会话是否登录：" + StpUtil.isLogin();
            return Result.ok(loginStatus);
        } catch (Exception e) {
            // 异常处理
            log.error("AdminUserController.isLogin.error:{}", e.getMessage(), e);
            return Result.fail("管理员用户查询登录状态失败");
        }
    }


    /**
     * 校验管理员用户信息
     *
     * @param authAdminUserDTO 管理员用户信息
     */
    private static void checkAdminUserInfo(AuthAdminUserDTO authAdminUserDTO) {
        Preconditions.checkNotNull(authAdminUserDTO, "管理员用户信息不能为空");
        Preconditions.checkNotNull(authAdminUserDTO.getUserName(), "管理员用户名不能为空");
    }
}
